import { CraftingManager } from '@/crafting/CraftingManager';
import { BlockType } from '@/blocks/types';
import { Inventory } from '@/player/Inventory';

export class CraftingUI {
  private craftingManager: CraftingManager;
  private inventory: Inventory;
  private craftingElement: HTMLElement | null = null;
  private isVisible = false;

  constructor(craftingManager: CraftingManager, inventory: Inventory) {
    this.craftingManager = craftingManager;
    this.inventory = inventory;
    this.createCraftingInterface();
  }

  private createCraftingInterface(): void {
    // 创建合成界面容器
    this.craftingElement = document.createElement('div');
    this.craftingElement.id = 'crafting-interface';
    this.craftingElement.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(0, 0, 0, 0.8);
      border: 2px solid #666;
      border-radius: 8px;
      padding: 20px;
      display: none;
      z-index: 1000;
      color: white;
      font-family: monospace;
    `;

    // 创建标题
    const title = document.createElement('h3');
    title.textContent = '工作台';
    title.style.cssText = `
      margin: 0 0 15px 0;
      text-align: center;
      color: #fff;
    `;
    this.craftingElement.appendChild(title);

    // 创建合成网格容器
    const craftingContainer = document.createElement('div');
    craftingContainer.style.cssText = `
      display: flex;
      gap: 20px;
      align-items: center;
    `;

    // 创建3x3合成网格
    const craftingGrid = document.createElement('div');
    craftingGrid.id = 'crafting-grid';
    craftingGrid.style.cssText = `
      display: grid;
      grid-template-columns: repeat(3, 40px);
      grid-template-rows: repeat(3, 40px);
      gap: 2px;
      background: #333;
      padding: 5px;
      border-radius: 4px;
    `;

    // 创建9个合成槽位
    for (let row = 0; row < 3; row++) {
      for (let col = 0; col < 3; col++) {
        const slot = document.createElement('div');
        slot.className = 'crafting-slot';
        slot.dataset.row = row.toString();
        slot.dataset.col = col.toString();
        slot.style.cssText = `
          width: 40px;
          height: 40px;
          background: #555;
          border: 1px solid #777;
          border-radius: 2px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          font-size: 12px;
          color: #fff;
        `;
        
        slot.addEventListener('click', (e) => this.handleSlotClick(e));
        craftingGrid.appendChild(slot);
      }
    }

    // 创建箭头
    const arrow = document.createElement('div');
    arrow.textContent = '→';
    arrow.style.cssText = `
      font-size: 24px;
      color: #fff;
    `;

    // 创建结果槽位
    const resultSlot = document.createElement('div');
    resultSlot.id = 'result-slot';
    resultSlot.style.cssText = `
      width: 40px;
      height: 40px;
      background: #555;
      border: 1px solid #777;
      border-radius: 2px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-size: 12px;
      color: #fff;
    `;
    resultSlot.addEventListener('click', () => this.handleResultClick());

    craftingContainer.appendChild(craftingGrid);
    craftingContainer.appendChild(arrow);
    craftingContainer.appendChild(resultSlot);
    this.craftingElement.appendChild(craftingContainer);

    // 创建按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.style.cssText = `
      margin-top: 15px;
      display: flex;
      gap: 10px;
      justify-content: center;
    `;

    // 创建清空按钮
    const clearButton = document.createElement('button');
    clearButton.textContent = 'Clear All';
    clearButton.style.cssText = `
      padding: 8px 16px;
      background: #f44336;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
    `;
    clearButton.addEventListener('click', () => this.clearCraftingGrid());
    buttonContainer.appendChild(clearButton);

    // 创建关闭按钮
    const closeButton = document.createElement('button');
    closeButton.textContent = 'Close';
    closeButton.style.cssText = `
      padding: 8px 16px;
      background: #666;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
    `;
    closeButton.addEventListener('click', () => this.hide());
    buttonContainer.appendChild(closeButton);

    this.craftingElement.appendChild(buttonContainer);

    document.body.appendChild(this.craftingElement);
  }

  private handleSlotClick(event: Event): void {
    const slot = event.target as HTMLElement;
    const row = parseInt(slot.dataset.row || '0');
    const col = parseInt(slot.dataset.col || '0');

    const selectedItem = this.inventory.getSelectedItem();
    const currentSlot = this.craftingManager.getGridSlot(row, col);

    if ((event as MouseEvent).shiftKey) {
      // Shift+点击：清空槽位
      if (currentSlot && currentSlot.type !== null) {
        // 将物品返回到物品栏
        this.inventory.addItem(currentSlot.type, currentSlot.count);
        this.craftingManager.setGridSlot(row, col, null, 0);
      }
    } else if (selectedItem && selectedItem.count > 0) {
      // 左键：放置物品
      if (currentSlot && currentSlot.type === selectedItem.type) {
        // 增加数量（最多64个）
        const canAdd = Math.min(selectedItem.count, 64 - currentSlot.count);
        if (canAdd > 0) {
          this.craftingManager.setGridSlot(row, col, selectedItem.type, currentSlot.count + 1);
          this.inventory.removeItem(selectedItem.type, 1);
        }
      } else if (!currentSlot || currentSlot.type === null) {
        // 放置新物品
        this.craftingManager.setGridSlot(row, col, selectedItem.type, 1);
        this.inventory.removeItem(selectedItem.type, 1);
      } else {
        // 交换物品
        const tempType = currentSlot.type;
        const tempCount = currentSlot.count;
        this.craftingManager.setGridSlot(row, col, selectedItem.type, 1);
        this.inventory.removeItem(selectedItem.type, 1);
        this.inventory.addItem(tempType, tempCount);
      }
    } else if (currentSlot && currentSlot.type !== null) {
      // 没有选中物品时，拿取槽位中的物品
      this.inventory.addItem(currentSlot.type, currentSlot.count);
      this.craftingManager.setGridSlot(row, col, null, 0);
    }

    this.updateDisplay();
  }

  private handleResultClick(): void {
    const success = this.craftingManager.executeCrafting(this.inventory);
    if (success) {
      this.updateDisplay();
    }
  }

  private updateDisplay(): void {
    if (!this.craftingElement) return;

    // 更新合成网格显示
    const craftingGrid = this.craftingElement.querySelector('#crafting-grid');
    if (craftingGrid) {
      const slots = craftingGrid.querySelectorAll('.crafting-slot');
      slots.forEach((slot, index) => {
        const row = Math.floor(index / 3);
        const col = index % 3;
        const gridSlot = this.craftingManager.getGridSlot(row, col);
        
        if (gridSlot && gridSlot.type !== null) {
          slot.textContent = this.getBlockDisplayName(gridSlot.type);
          (slot as HTMLElement).style.background = '#777';
        } else {
          slot.textContent = '';
          (slot as HTMLElement).style.background = '#555';
        }
      });
    }

    // 更新结果槽位显示
    const resultSlot = this.craftingElement.querySelector('#result-slot');
    if (resultSlot) {
      const result = this.craftingManager.checkCurrentRecipe();
      if (result && result.canCraft) {
        resultSlot.textContent = this.getBlockDisplayName(result.recipe.result.type);
        (resultSlot as HTMLElement).style.background = '#4CAF50';
      } else {
        resultSlot.textContent = '';
        (resultSlot as HTMLElement).style.background = '#555';
      }
    }
  }

  private getBlockDisplayName(blockType: BlockType): string {
    const names: Partial<Record<BlockType, string>> = {
      [BlockType.AIR]: '',
      [BlockType.GRASS]: '草',
      [BlockType.DIRT]: '土',
      [BlockType.STONE]: '石',
      [BlockType.LOG]: '木',
      [BlockType.PLANKS]: '板',
      [BlockType.COAL_ORE]: '煤',
      [BlockType.LAVA]: '岩',
      [BlockType.FURNACE]: '炉',
      [BlockType.TORCH]: '火',
      [BlockType.CRAFTING_TABLE]: '台',
      [BlockType.SAND]: '沙',
      [BlockType.SANDSTONE]: '砂岩',
      [BlockType.GLASS]: '玻璃',
      [BlockType.IRON_ORE]: '铁矿',
      [BlockType.GOLD_ORE]: '金矿',
      [BlockType.DIAMOND_ORE]: '钻石',
      [BlockType.WATER]: '水',
      [BlockType.OBSIDIAN]: '黑曜石',
      [BlockType.REDSTONE_WIRE]: '红石',
      [BlockType.REDSTONE_TORCH]: '红石火把',
      [BlockType.COBBLESTONE]: '圆石',
      [BlockType.GRAVEL]: '沙砾',
      [BlockType.CLAY]: '粘土',
      [BlockType.BRICK]: '砖',
      [BlockType.SNOW]: '雪'
    };
    return names[blockType] || '?';
  }

  public show(): void {
    if (this.craftingElement) {
      this.craftingElement.style.display = 'block';
      this.isVisible = true;
      this.craftingManager.openCraftingTable();
      this.updateDisplay();
    }
  }

  public hide(): void {
    if (this.craftingElement) {
      this.craftingElement.style.display = 'none';
      this.isVisible = false;
      this.craftingManager.closeCraftingTable();
    }
  }

  public isOpen(): boolean {
    return this.isVisible;
  }

  public toggle(): void {
    if (this.isVisible) {
      this.hide();
    } else {
      this.show();
    }
  }

  private clearCraftingGrid(): void {
    // 将合成网格中的所有物品返回到物品栏
    for (let row = 0; row < 3; row++) {
      for (let col = 0; col < 3; col++) {
        const gridSlot = this.craftingManager.getGridSlot(row, col);
        if (gridSlot && gridSlot.type !== null) {
          // 尝试将物品添加到物品栏
          const result = this.inventory.addItemWithOverflow(gridSlot.type, gridSlot.count);
          
          // 如果物品栏满了，显示提示
          if (result.overflow > 0) {
            this.showNotification(`Inventory full! ${result.overflow} items will be dropped.`);
            // 这里可以添加掉落物品的逻辑
          }
          
          // 清空合成槽位
          this.craftingManager.setGridSlot(row, col, null, 0);
        }
      }
    }
    
    this.updateDisplay();
    this.showNotification('Crafting grid cleared!');
  }

  private showNotification(message: string): void {
    const notification = document.createElement('div');
    notification.textContent = message;
    notification.style.cssText = `
      position: fixed;
      top: 20%;
      left: 50%;
      transform: translateX(-50%);
      background: rgba(76, 175, 80, 0.9);
      color: white;
      padding: 10px 20px;
      border-radius: 5px;
      z-index: 3000;
      font-weight: bold;
      pointer-events: none;
      font-size: 14px;
    `;
    
    document.body.appendChild(notification);
    
    // 2秒后移除通知
    setTimeout(() => {
      if (notification.parentNode) {
        document.body.removeChild(notification);
      }
    }, 2000);
  }
}